package finder

import (
	"log"
	"os"
	"time"
	"errors"

	"golang.org/x/net/context"
	"google.golang.org/grpc"
	pb "change.tm/finder/pb"
)

func Register(name string, address []string, port string) {
	time.Sleep(time.Second)

	conn, err := grpc.Dial("api.change.tm:3005", grpc.WithInsecure())
	if err != nil {
		log.Fatalf("[ ERROR ] - 无法连接到服务发现层 : %v", err)
		os.Exit(1)
	}
	defer conn.Close()
	c := pb.NewFinderClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	r, err := c.Register(ctx, &pb.RegisterRequest{Name: name, Address: address, Port:port})
	if err != nil {
		log.Fatalf("[ ERROR ] - 服务注册失败，无法进行远程调用 : %v", err)
		os.Exit(1)
	}

	if r.Result {
		log.Println("[ INFO ] - 服务注册成功")
	} else {
		log.Fatalf("[ ERROR ] - 服务注册失败，无法进行通信")
		os.Exit(1)
	}
}

func GetService(name string) (string, string, error) {
	conn, err := grpc.Dial("api.change.tm:3005", grpc.WithInsecure())
	if err != nil {
		return "", "", err
	}
	defer conn.Close()
	c := pb.NewFinderClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	r, err := c.GetService(ctx, &pb.GetServiceRequest{Name: name})
	if err != nil {
		return "", "", err
	}

	if r.Address!="" && r.Port!="" {
		return r.Address, r.Port, nil
	} else {
		return "", "", errors.New("未获取到服务信息")
	}
}